/**
 * 微信公众号平台处理器
 * 简单的格式转换和基本校验
 */

import { createLogger, ILogger } from '../../utils/logger';
import { 
  PublishPlatform, 
  IContent, 
  IValidationResult, 
  IPublishOptions, 
  IPublishResult, 
  IPlatformHandler 
} from './interfaces';

export class WechatMpPlatform implements IPlatformHandler {
  public readonly platform = PublishPlatform.WECHAT_MP;
  private readonly logger: ILogger;

  constructor(logger?: ILogger) {
    this.logger = logger || createLogger('WechatMpPlatform');
  }

  /**
   * 格式化内容 - 转换为微信公众号支持的HTML格式
   */
  async formatContent(content: IContent): Promise<IContent> {
    const formatted = { ...content };

    try {
      // 1. 转换为HTML格式
      if (content.format === 'markdown') {
        formatted.content = this.markdownToHtml(content.content);
        formatted.format = 'html';
      }

      // 2. 清理不支持的HTML标签
      formatted.content = this.cleanHtml(formatted.content);

      // 3. 处理标题长度限制（微信公众号限制64字符）
      if (formatted.title.length > 64) {
        formatted.title = formatted.title.substring(0, 61) + '...';
        this.logger.warn('Title truncated to 64 characters for WeChat MP');
      }

      // 4. 微信公众号不支持标签，移除标签
      formatted.tags = undefined;

      return formatted;
    } catch (error) {
      this.logger.error('Failed to format content for WeChat MP', error as Error);
      return content;
    }
  }

  /**
   * 验证内容
   */
  validateContent(content: IContent): IValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // 基本验证
    if (!content.title || content.title.trim().length === 0) {
      errors.push('标题不能为空');
    }

    if (!content.content || content.content.trim().length === 0) {
      errors.push('内容不能为空');
    }

    // 微信公众号特定验证
    if (content.title.length > 64) {
      warnings.push('标题长度超过64字符，将被截断');
    }

    const textLength = content.content.replace(/<[^>]*>/g, '').length;
    if (textLength > 20000) {
      errors.push('内容长度超过微信公众号限制（20,000字符）');
    }

    if (textLength < 50) {
      warnings.push('内容长度较短，建议至少50字符');
    }

    // 检查外部链接
    const externalLinks = content.content.match(/<a[^>]*href="([^"]*)"[^>]*>/gi);
    if (externalLinks && externalLinks.length > 0) {
      const hasExternal = externalLinks.some(link => 
        !link.includes('weixin.qq.com') && !link.includes('mp.weixin.qq.com')
      );
      if (hasExternal) {
        warnings.push('微信公众号不支持外部链接，将被移除');
      }
    }

    // 检查敏感词
    const sensitiveWords = /(微信|WeChat|公众号)/i;
    if (sensitiveWords.test(content.title) || sensitiveWords.test(content.content)) {
      warnings.push('内容可能包含敏感词汇，发布时请注意');
    }

    return {
      valid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 发布内容
   */
  async publish(content: IContent, options?: IPublishOptions): Promise<IPublishResult> {
    try {
      this.logger.info('Publishing to WeChat MP...');

      // 格式化内容
      const formattedContent = await this.formatContent(content);

      // 验证内容
      const validation = this.validateContent(formattedContent);
      if (!validation.valid) {
        return {
          success: false,
          error: `Validation failed: ${validation.errors.join(', ')}`
        };
      }

      // TODO: 实际的发布逻辑
      // 这里应该调用微信公众号的API或使用自动化工具发布
      
      this.logger.info('Content published to WeChat MP successfully');
      
      return {
        success: true,
        url: 'https://mp.weixin.qq.com/cgi-bin/appmsg',
        articleId: 'example-id',
        metadata: {
          platform: 'wechat_mp',
          publishTime: new Date(),
          isDraft: options?.isDraft || false
        }
      };

    } catch (error) {
      this.logger.error('Failed to publish to WeChat MP', error as Error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * Markdown转HTML - 简单转换
   */
  private markdownToHtml(markdown: string): string {
    return markdown
      // 标题
      .replace(/^# (.*$)/gim, '<h1>$1</h1>')
      .replace(/^## (.*$)/gim, '<h2>$1</h2>')
      .replace(/^### (.*$)/gim, '<h3>$1</h3>')
      .replace(/^#### (.*$)/gim, '<h4>$1</h4>')
      .replace(/^##### (.*$)/gim, '<h5>$1</h5>')
      .replace(/^###### (.*$)/gim, '<h6>$1</h6>')
      
      // 格式化
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      .replace(/`(.*?)`/g, '<code>$1</code>')
      
      // 链接和图片
      .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
      .replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">')
      
      // 列表
      .replace(/^\* (.*$)/gim, '<li>$1</li>')
      .replace(/^- (.*$)/gim, '<li>$1</li>')
      .replace(/^(\d+)\. (.*$)/gim, '<li>$1</li>')
      
      // 引用和代码块
      .replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
      .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
      
      // 换行和段落
      .replace(/\n\n/g, '</p><p>')
      .replace(/\n/g, '<br>')
      
      // 包装段落
      .replace(/^(.+)$/gm, '<p>$1</p>')
      
      // 清理空段落
      .replace(/<p><\/p>/g, '');
  }

  /**
   * 清理HTML - 移除不支持的标签和外部链接
   */
  private cleanHtml(html: string): string {
    return html
      // 移除脚本和样式
      .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gim, '')

      // 移除不支持的标签
      .replace(/<(iframe|object|embed|form|video|audio)[^>]*>[\s\S]*?<\/\1>/gim, '')
      
      // 处理外部链接 - 转换为纯文本
      .replace(/<a[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/gi, (match, href, text) => {
        if (!href.includes('weixin.qq.com') && !href.includes('mp.weixin.qq.com')) {
          return text; // 外部链接转为纯文本
        }
        return match;
      })
      
      // 清理空标签
      .replace(/<(\w+)[^>]*>\s*<\/\1>/gi, '');
  }
}
